import os
from PyQt5.QtGui import *

from UI.loginManage import *
from UI.homeManage import *
from UI.homeWorkingManage import *
from UI.doneManage import *
# from UI.loadManage import *
from util.http.httpUtil import HttpUtil
from util.serial.serialUtil import SerialUtil
from util.thread.threadUtil import ThreadUtil
from util.log.runTimeLogUtil import RunTimeLogUtil
from PyQt5.QtCore import *

http = HttpUtil()
serial = SerialUtil()
thread = ThreadUtil()
log = RunTimeLogUtil(path="./log/")

null = ""
true = True
false = False

class Main():
    def __init__(self):
        import sys
        app = QtWidgets.QApplication(sys.argv)
        self.LoginForm = QtWidgets.QWidget()
        self.HomeForm = QtWidgets.QWidget()
        self.HomeWorkingFrom = QtWidgets.QWidget()
        self.DoneFrom = QtWidgets.QWidget()
        # self.LoadFrom = QtWidgets.QWidget()

        self.loginui = LoginUi()
        self.loginui.setupUi(self.LoginForm)
        self.homeuui = HomeUI()
        self.homeuui.setupUi(self.HomeForm)
        self.homewui = HomeWorkingUI()
        self.homewui.setupUi(self.HomeWorkingFrom)
        self.doneui = DoneUI()
        self.doneui.setupUi(self.DoneFrom)
        # self.loadui = LoadUI()
        # self.loadui.setupUi(self.LoadFrom)

        self.init()
        os._exit(app.exec_())

    def init(self):
        self.message1 = message(self)
        self.message1.signal.connect(self.box)

        self.serial = False
        self.cbs = []
        self.cbarcodes = {}
        self.printed = 'false'

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("./static/logo.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.LoginForm.setWindowIcon(icon)
        self.HomeForm.setWindowIcon(icon)
        self.HomeWorkingFrom.setWindowIcon(icon)
        self.DoneFrom.setWindowIcon(icon)

        self.loginui.loginHandle = self.login
        self.homeuui.sopenHandle = self.open
        self.homeuui.scloseHandle = self.close
        self.homeuui.backHandle = self.back
        self.homeuui.nextHandle = self.next
        self.homeuui.refreshHandle = self.refresh
        self.homeuui.searchHandle = self.getFlowCards
        self.homeuui.textChangeHandle = self.textChange

        self.homewui.stopHandle = self.stop
        self.doneui.returnHandle = self.returnHome
        self.doneui.printHandle = self.printCode
        self.doneui.againHandle = self.again
        self.doneui.allHandle = self.all

        self.LoginForm.resize(1200, 573)
        self.HomeForm.resize(1880, 700)
        self.HomeWorkingFrom.resize(1880, 700)
        self.DoneFrom.resize(1880, 800)

        self.loginui.init()
        self.LoginForm.show()

        self.message = QtWidgets.QMessageBox

        # self.switchBtn = SwitchButton(self.HomeForm)
        # self.switchBtn.setMinimumSize(QtCore.QSize(50, 35))
        # self.switchBtn.setMaximumSize(QtCore.QSize(120, 16777215))
        # self.switchBtn.setStyleSheet("/*按钮普通态*/\n"
        #                              "QPushButton {\n"
        #                              "    /*字体为微软雅黑*/\n"
        #                              "    font-family: Microsoft Yahei;\n"
        #                              "    /*字体大小为20点*/\n"
        #                              "    font-size: 11pt;\n"
        #                              "    /*字体颜色为白色*/\n"
        #                              "    color: #000000;\n"
        #                              "    /*背景颜色*/\n"
        #                              "    background-color: #ffffff;\n"
        #                              "    outline: none;\n"
        #                              "    border-radius: 5px;\n"
        #                              "    border: 1px solid #dddddd;\n"
        #                              "}\n"
        #                              "QPushButton:hover {\n"
        #                              "    border: 1px solid #7084D4;\n"
        #                              "}\n"
        #                              "QPushButton:pressed {\n"
        #                              "    padding-left: 3px;\n"
        #                              "    padding-top: 3px;\n"
        #                              "}")
        # self.homeuui.gridLayout_6.addWidget(self.switchBtn, 0, 3, 1, 1)
        # self.switchBtn.checkedChanged.connect(self.refresh)

        try:
            with open("./config/main.config", "r") as fp:
                data = fp.read()
                self.requestStr = data
        except Exception as e:
            print(e)

        try:
            with open("./config/http.config", "r") as fp:
                data = fp.read()
                http.baseURL = f"http://{data}/packer/"
        except Exception as e:
            print(e)

    def login(self):
        username = self.loginui.username_LE.text()
        password = self.loginui.password_LE.text()
        if (username == "admin" and password == 'admin'):
            # self.message.information(self.HomeForm, "登录成功", "加载中，请稍等")
            log.fileLog("登录成功")
            self.LoginForm.close()

            self.getSerialPorts()
            self.getFlowCards()
            self.homeuui.init()
            self.homewui.init()
            self.doneui.init()
            self.HomeForm.show()  # 最大化展示
        else:
            print("登录失败")
            log.fileLog(f"登录失败")
            self.message.critical(self.LoginForm, "登录失败", "账号或密码错误")

    def getFlowCards(self, start='0', limit='20'):
        searchText = self.homeuui.searchtextLE.text()
        try:
            if(searchText):
                url = f"getFlowCards.do?start={start}&limit={limit}&searchText={searchText}&printed={self.printed}"
            else:
                url = f"getFlowCards.do?start={start}&limit={limit}&printed={self.printed}"
            # print(http.baseURL+url)
            rs = eval(http.get(url, timeout=3))
        except:
            self.message.critical(self.HomeForm, "获取流转卡列表失败", "请检查网络是否正常连接")
            os._exit(0)
        if (rs['success']):
            data = rs['data']
            total = data['total']
            self.limit = int(limit)
            if (int(total) % int(limit)):
                self.page = int(int(total)/int(limit))+1
            else:
                self.page = int(int(total)/int(limit))
            self.currpage = int(int(start)/int(limit) + 1)
            self.homeuui.pageL.setText(f"{self.currpage} / {self.page}")
            self.homewui.pageL.setText(f"{self.currpage} / {self.page}")
            cards = data['cards']
            self.homeuui.totalL.setText(f"共 {total} 条")
            self.homewui.totalL.setText(f"共 {total} 条")
            self.homeuui.cardsTW.setRowCount(len(cards))
            self.homewui.cardsTW.setRowCount(len(cards))
            if (self.currpage == 1): self.homeuui.backPB.setEnabled(False)
            else: self.homeuui.backPB.setEnabled(True)
            if (self.currpage == self.page): self.homeuui.nextPB.setEnabled(False)
            else: self.homeuui.nextPB.setEnabled(True)
            for i in range(0, len(cards)):
                self.homeuui.cardsTW.setItem(i, 0, QTableWidgetItem(str(cards[i]['id'])))
                self.homeuui.cardsTW.setItem(i, 1, QTableWidgetItem(cards[i]['code']))
                self.homeuui.cardsTW.setItem(i, 2, QTableWidgetItem(cards[i]['productCode']))
                self.homeuui.cardsTW.setItem(i, 3, QTableWidgetItem(cards[i]['productName']))
                self.homeuui.cardsTW.setItem(i, 4, QTableWidgetItem(cards[i]['productModel']))
                self.homeuui.cardsTW.setItem(i, 5, QTableWidgetItem(cards[i]['unitName']))
                # self.homeuui.cardsTW.setItem(i, 6, QTableWidgetItem(str(cards[i]['achieveQty'])))
                self.homeuui.cardsTW.setItem(i, 7, QTableWidgetItem(str(cards[i]['binCapacity'])))
                self.homeuui.cardsTW.setItem(i, 8, QTableWidgetItem(cards[i]['printFormat']))
                self.homeuui.cardsTW.setItem(i, 9, QTableWidgetItem(str(cards[i]['cardCount'])))
                self.homeuui.cardsTW.setItem(i, 10, QTableWidgetItem(str(cards[i]['printedCardCount'])))
                self.homeuui.cardsTW.setCellWidget(i, 11, self.addButton(i, cards[i]['id'], cards[i]['cardCount'] > cards[i]['printedCardCount']))

                self.homewui.cardsTW.setItem(i, 0, QTableWidgetItem(str(cards[i]['id'])))
                self.homewui.cardsTW.setItem(i, 1, QTableWidgetItem(cards[i]['code']))
                self.homewui.cardsTW.setItem(i, 2, QTableWidgetItem(cards[i]['productCode']))
                self.homewui.cardsTW.setItem(i, 3, QTableWidgetItem(cards[i]['productName']))
                self.homewui.cardsTW.setItem(i, 4, QTableWidgetItem(cards[i]['productModel']))
                self.homewui.cardsTW.setItem(i, 5, QTableWidgetItem(cards[i]['unitName']))
                # self.homewui.cardsTW.setItem(i, 6, QTableWidgetItem(str(cards[i]['achieveQty'])))
                self.homewui.cardsTW.setItem(i, 7, QTableWidgetItem(str(cards[i]['binCapacity'])))
                self.homewui.cardsTW.setItem(i, 8, QTableWidgetItem(cards[i]['printFormat']))
                self.homewui.cardsTW.setItem(i, 9, QTableWidgetItem(str(cards[i]['cardCount'])))
                self.homewui.cardsTW.setItem(i, 10, QTableWidgetItem(str(cards[i]['printedCardCount'])))
                self.homewui.cardsTW.setCellWidget(i, 11, self.addButton(i, cards[i]['id'],
                                                                         cards[i]['cardCount'] > cards[i][
                                                                             'printedCardCount']))
        else: print(rs['errMsg'])

    def getSerialPorts(self):
        self.homeuui.portCB.clear()
        portList = []
        for item in serial.getPortList():
            portList.append(item[0])
        if not portList:
            portList = ["未检测到串口"]
        self.homeuui.portCB.addItems(portList)

    def buttonWidgetForRow(self, id):
        widget = QWidget()

        # 修改
        updateBtn = QPushButton('修改')
        updateBtn.setStyleSheet(''' text-align : center;
                                          background-color : NavajoWhite;
                                          height : 30px;
                                          border-style: outset;
                                          font : 13px  ''')

        updateBtn.clicked.connect(lambda: self.updateTable(id))

        # 查看
        viewBtn = QPushButton('查看')
        viewBtn.setStyleSheet(''' text-align : center;
                                  background-color : DarkSeaGreen;
                                  height : 30px;
                                  border-style: outset;
                                  font : 13px; ''')

        viewBtn.clicked.connect(lambda: self.viewTable(id))

        # 删除
        deleteBtn = QPushButton('删除')
        deleteBtn.setStyleSheet(''' text-align : center;
                                    background-color : LightCoral;
                                    height : 30px;
                                    border-style: outset;
                                    font : 13px; ''')

        hLayout = QHBoxLayout()
        hLayout.addWidget(updateBtn)
        hLayout.addWidget(viewBtn)
        hLayout.addWidget(deleteBtn)
        hLayout.setContentsMargins(5, 2, 5, 2)
        widget.setLayout(hLayout)
        return widget

    def addButton(self, index, id, status):
        widget = QWidget()
        widget.setStyleSheet('border: 0px solid black;')

        # 开始
        beginBtn = QPushButton('开始喷印')
        if (status):
            beginBtn.setStyleSheet(''' text-align : center;
                                                  color : rgb(0, 0, 255);
                                                  height : 30px;
                                                  border-style: outset;
                                                  font : 13px  ''')
        else:
            beginBtn.setStyleSheet(''' text-align : center;
                                                              color : rgb(150, 150, 150);
                                                              height : 30px;
                                                              font : 13px  ''')
        beginBtn.setEnabled(status)

        beginBtn.clicked.connect(lambda: self.begin(index, id))

        # 查看
        viewBtn = QPushButton('查看已喷印条码')
        viewBtn.setStyleSheet(''' text-align : center;
                                                      color : rgb(0, 0, 255);
                                                      height : 30px;
                                                      font : 13px  ''')

        viewBtn.clicked.connect(lambda: self.view(index))

        hLayout = QHBoxLayout()
        hLayout.addWidget(beginBtn)
        hLayout.addWidget(viewBtn)
        hLayout.setContentsMargins(5, 2, 2, 5)
        widget.setLayout(hLayout)
        return widget

    def begin(self, index, id):
        if (self.homeuui.cardsTW.item(index, 10).text() == self.homeuui.cardsTW.item(index, 9).text()):
            self.message.warning(self.HomeForm, "警告", "该产品已喷印完成")
            return
        elif(not self.serial):
            self.message.warning(self.HomeForm, "警告", "请先打开串口")
            return
        self.HomeForm.hide()
        self.HomeWorkingFrom.show()

        self.homewui.flowCardIdL.setText(self.homeuui.cardsTW.item(index, 0).text())
        self.homewui.flowCardCodeL.setText(self.homeuui.cardsTW.item(index, 1).text())
        self.homewui.productCodeL.setText(self.homeuui.cardsTW.item(index, 2).text())
        self.homewui.productNameL.setText(self.homeuui.cardsTW.item(index, 3).text())
        self.homewui.productModelL.setText(self.homeuui.cardsTW.item(index, 4).text())
        def begin():
            serial.ser.flushInput()
            serial.ser.flushOutput()
            lastBarcodeId = ""
            while True:
                # try:
                    result = serial.sub(len(self.requestStr))
                    if (result == self.requestStr):
                        print(f"接收到来自喷码机请求喷印消息：{result}")
                        log.runFileLog(f"接收到来自喷码机请求喷印消息：{result}")
                        if (lastBarcodeId):
                            try:
                                rs = eval(http.get(f"printed.do?flowCardId={id}&barcodeId={lastBarcodeId}", timeout=3))
                            except Exception as e:
                                print(f"设置条码为已打印状态出错：{e}")
                                log.exceptFileLog(
                                    f"设置条码为已打印状态出错：{e}；请求为：{http.baseURL}printed.do?flowCardId={id}&barcodeId={barcodeId}")
                                continue
                            if (rs['success']):
                                print(f"设置条码为已打印状态成功")
                                log.runFileLog(f"设置条码为已打印状态成功")
                                lastBarcodeId = ""
                                self.homeuui.cardsTW.setItem(index, 10, QTableWidgetItem(
                                    str(int(self.homeuui.cardsTW.item(index, 10).text()) + 1)))
                                if (self.homeuui.cardsTW.item(index, 10).text() == self.homeuui.cardsTW.item(index,
                                                                                                             9).text()):
                                    # self.stop()
                                    # self.getFlowCards(str((self.currpage - 1) * self.limit))
                                    self.message1.start()
                                    # win32api.ShellExecute(0, 'open', 'message.exe', '', '', 1)
                                    # os.system("message.exe")
                                    # self.message.information(self.HomeWorkingFrom, "喷印完成", "当前所有条码已喷印完成")
                                    break
                            else:
                                print(f"设置条码为已打印状态失败：{rs['errMsg']}")
                                log.runFileLog(f"设置条码为已打印状态失败：{rs['errMsg']}")
                                self.homewui.barcodeIdL.setText("设置条码为已打印状态失败")
                                self.homewui.codeL.setText(str(rs['errMsg']))
                                continue
                        try:
                            rs = eval(http.get(f"getUnprintBarcodes.do?flowCardId={id}", timeout=3))
                        except Exception as e:
                            log.exceptFileLog(f"获取未打印条码列表出错：{e}；请求为：{http.baseURL}getUnprintBarcodes.do?flowCardId={id}")
                            continue
                        if (rs['success']):
                            log.runFileLog(f"获取未打印条码列表成功：{rs['data']}")
                            data = rs['data']
                            barcodes = data['barcodes']
                            flowCard = barcodes[0]
                            barcodeId = flowCard['id']
                            code = flowCard['code']
                            self.homewui.barcodeIdL.setText(str(barcodeId))
                            self.homewui.codeL.setText(str(code))
                            result = serial.pub(code + '\r\n')
                            if (result == len(code + '\r\n')):
                                data = serial.sub(len(code))
                                if (data == code):
                                    print(f"接收到来自喷码机喷印完成消息：{data}")
                                    log.runFileLog(f"接收到来自喷码机喷印完成消息：{data}")
                                    lastBarcodeId = barcodeId
                                else:
                                    print(f"接收来自喷码机喷印完成消息出错：应接收>>>{code}<<<，实际接收>>>{data}<<<（若接收值为空或不全，可能是接收超时）")
                                    log.runFileLog(f"接收来自喷码机喷印完成消息出错：应接收>>>{code}<<<，实际接收>>>{data}<<<（若接收值为空或不全，可能是接收超时）")
                                    continue
                            else:
                                print(f"向喷码机发送条码号出错：应发送>>>{len(code + 2)}位{code}，实际发送了{result}位")
                                log.runFileLog(f"向喷码机发送条码号出错：应发送>>>{len(code + 2)}位{code}，实际发送了{result}位")
                        else:
                            print(f"获取未打印条码列表失败：{rs['errMsg']}")
                            log.runFileLog(f"获取未打印条码列表失败：{rs['errMsg']}")
                            self.homewui.barcodeIdL.setText("获取未打印条码列表失败")
                            self.homewui.codeL.setText(str(rs['errMsg']))
                            continue
                    else:
                        print(f"接收来自喷码机准备就绪消息出错：应接收>>>{self.requestStr}<<<，实际接收>>>{result}<<<（若接收值为空或不全，可能是接收超时）")
                        log.runFileLog(f"接收来自喷码机准备就绪消息出错：应接收>>>{self.requestStr}<<<，实际接收>>>{result}<<<（若接收值为空或不全，可能是接收超时）")
                        continue
                # except Exception as e:
                #     print(f"异常：{e}")
                #     log.exceptFileLog(e)

        thread.startThread(begin)

    def stop(self):
        self.homewui.barcodeIdL.setText("NULL")
        self.homewui.codeL.setText("NULL")
        self.HomeWorkingFrom.hide()
        self.HomeForm.show()
        thread.stopThread()

    def open(self):
        try:
            port = self.homeuui.portCB.currentText()
            bps = int(self.homeuui.bpsCB.currentText())
            if self.homeuui.timeoutLE.text() == "None":
                timeout = None
            else:
                timeout = int(self.homeuui.timeoutLE.text()) / 1000
            serial.open(port, bps, timeout)
            if (serial.ser):
                self.serial = True
                self.homeuui.openPB.setEnabled(False)
                self.homeuui.closePB.setEnabled(True)
                self.message.information(self.HomeForm, "成功", "打开串口成功")
                self.save()
                log.runFileLog("打开串口成功")
            else:
                self.serial = False
                self.homeuui.openPB.setEnabled(True)
                self.homeuui.closePB.setEnabled(False)
                self.message.critical(self.HomeForm, "失败", "打开串口失败")
                log.runFileLog("打开串口失败")
        except Exception as e:
            log.exceptFileLog(f"打开串口出错：{e}")

    def close(self):
        if (self.serial):
            serial.close()
            self.serial = False
            self.homeuui.openPB.setEnabled(True)
            self.homeuui.closePB.setEnabled(False)
            self.message.information(self.HomeForm, "成功", "关闭串口成功")
            log.runFileLog("关闭串口成功")

    def save(self):
        print(self.homeuui.portCB.currentText(), self.homeuui.bpsCB.currentText(), self.homeuui.timeoutLE.text())
        data = f"{self.homeuui.portCB.currentText()},{self.homeuui.bpsCB.currentText()},{self.homeuui.timeoutLE.text()}"
        with open("./config/serial.config", "w+") as fp:
            fp.write(data)

    def refresh(self, i):
        if (i):
            self.printed = 'true'
        else:
            self.printed = 'false'
        self.getFlowCards()


    def next(self):
        # 先获得总行数 rowPosition
        rowPosition = self.homeuui.cardsTW.rowCount()
        # 这句是关键！ range(0, rowPosition)[::-1] 逆序循环
        for rP in range(0, rowPosition)[::-1]:
            self.homeuui.cardsTW.removeRow(rP)

        self.getFlowCards(str(self.currpage * self.limit))

    def back(self):
        # 先获得总行数 rowPosition
        rowPosition = self.homeuui.cardsTW.rowCount()
        # 这句是关键！ range(0, rowPosition)[::-1] 逆序循环
        for rP in range(0, rowPosition)[::-1]:
            self.homeuui.cardsTW.removeRow(rP)

        self.getFlowCards(str((self.currpage - 2) * self.limit))

    def view(self, index):
        if (not self.serial):
            self.message.warning(self.HomeForm, "警告", "请先打开串口")
            return
        self.message.information(self.HomeForm, "tip", "加载中，请稍等")
        id = self.homeuui.cardsTW.item(index, 0).text()
        code = self.homeuui.cardsTW.item(index, 1).text()
        productCode = self.homeuui.cardsTW.item(index, 2).text()
        productName = self.homeuui.cardsTW.item(index, 3).text()
        productModel = self.homeuui.cardsTW.item(index, 4).text()

        self.doneui.flowCardIdL.setText(str(id))
        self.doneui.flowCardCodeL.setText(str(code))
        self.doneui.productCodeL.setText(productCode)
        self.doneui.productNameL.setText(productName)
        self.doneui.productModelL.setText(productModel)
        try:
            rs = eval(http.get(f"getPrintedBarcodes.do?flowCardId={id}&top=1000000", timeout=3))
            if (rs['success']):
                barcodes = rs['data']['barcodes']
                self.hbarcodes = barcodes
                if(len(barcodes)):
                    self.doneui.cardsTW.setRowCount(len(barcodes))
                    self.doneui.totalL.setText(f"共 {len(barcodes)} 条")
                    for i in range(0, len(barcodes)):
                        self.doneui.cardsTW.setCellWidget(i, 0, self.addCheckBox(i))
                        self.doneui.cardsTW.setItem(i, 1, QTableWidgetItem(str(barcodes[i]['id'])))
                        self.doneui.cardsTW.setItem(i, 2, QTableWidgetItem(str(barcodes[i]['code'])))
                else:
                    self.message.information(self.DoneFrom, "tip", "该项任务已打印条码数为0")
                    return
        except Exception as e:
            print(e)

        if(os.path.exists(f"./config/flowCard/{id}.config")):
            with open(f"./config/flowCard/{id}.config", "r") as fp:
                data = eval(fp.read())
                total = data['total']
                count = data['count']

                self.doneui.totalL_2.setText(str(total))
                self.doneui.countL.setText(str(count))
        else:
            self.doneui.printPB.setEnabled(False)
            # self.message.information(self.DoneFrom, "tip", "该项任务无重新喷印计划")

        self.HomeForm.hide()
        self.DoneFrom.show()

    def printCode(self):
        def printCode():
            serial.ser.flushInput()
            serial.ser.flushOutput()
            lastBarcodeId = ""
            id = self.doneui.flowCardIdL.text()
            total = int(self.doneui.totalL_2.text())
            count = int(self.doneui.countL.text())
            while True:
                # try:
                    result = serial.sub(len(self.requestStr))
                    if (result == self.requestStr):
                        print(f"接收到来自喷码机请求喷印消息：{result}")
                        log.runFileLog(f"接收到来自喷码机请求喷印消息：{result}")
                        if (lastBarcodeId):
                            try:
                                rs = self.doneui.printed(id)
                            except Exception as e:
                                print(f"设置条码为已打印状态出错：{e}")
                                log.exceptFileLog(
                                    f"设置条码为已打印状态出错：{e}；")
                                continue
                            if (rs):
                                print(f"设置条码为已打印状态成功")
                                log.runFileLog(f"设置条码为已打印状态成功")
                                lastBarcodeId = ""
                                count += 1
                                self.doneui.countL.setText(str(count))
                                if (total == count):
                                    self.message1.start()
                                    # win32api.ShellExecute(0, 'open', 'message.exe', '', '', 1)
                                    # os.system("message.exe")
                                    # self.message.information(self.DoneFrom, "喷印完成", "当前所有条码已喷印完成")
                                    break
                            else:
                                print(f"设置条码为已打印状态失败")
                                log.runFileLog(f"设置条码为已打印状态失败")
                                continue
                        barcodes = self.doneui.getUnprintBarcodes(id)
                        if (barcodes):
                            log.runFileLog(f"获取未打印条码成功：{barcodes}")
                            barcodeId = barcodes['id']
                            code = barcodes['code']
                            self.doneui.barcodeIdL.setText(str(barcodeId))
                            self.doneui.codeL.setText(str(code))
                            result = serial.pub(code + '\r\n')
                            if (result == len(code + '\r\n')):
                                data = serial.sub(len(code))
                                if (data == code):
                                    print(f"接收到来自喷码机喷印完成消息：{data}")
                                    log.runFileLog(f"接收到来自喷码机喷印完成消息：{data}")
                                    lastBarcodeId = barcodeId
                                else:
                                    print(f"接收来自喷码机喷印完成消息出错：应接收>>>{code}<<<，实际接收>>>{data}<<<（若接收值为空或不全，可能是接收超时）")
                                    log.runFileLog(f"接收来自喷码机喷印完成消息出错：应接收>>>{code}<<<，实际接收>>>{data}<<<（若接收值为空或不全，可能是接收超时）")
                                    continue
                            else:
                                print(f"向喷码机发送条码号出错：应发送>>>{len(code + 2)}位{code}，实际发送了{result}位")
                                log.runFileLog(f"向喷码机发送条码号出错：应发送>>>{len(code)+2}位{code}，实际发送了{result}位")
                        else:
                            print(f"获取未打印条码失败")
                            log.runFileLog(f"获取未打印条码失败")
                            continue
                    else:
                        print(f"接收来自喷码机准备就绪消息出错：应接收>>>{self.requestStr}<<<，实际接收>>>{result}<<<（若接收值为空或不全，可能是接收超时）")
                        log.runFileLog(f"接收来自喷码机准备就绪消息出错：应接收>>>{self.requestStr}<<<，实际接收>>>{result}<<<（若接收值为空或不全，可能是接收超时）")
                        continue
                # except Exception as e:
                #     print(f"异常：{e}")
                #     log.exceptFileLog(e)
        if (self.doneui.printPB.text() == "开始喷印"):
            if (int(self.doneui.countL.text()) >= int(self.doneui.totalL_2.text())): return
            thread.startThread(printCode)
            self.doneui.printPB.setText("暂停")
            self.doneui.frame.setEnabled(False)
        else:
            thread.stopThread()
            self.doneui.printPB.setText("开始喷印")
            self.doneui.frame.setEnabled(True)

    def returnHome(self):
        # 先获得总行数 rowPosition
        rowPosition = self.doneui.cardsTW.rowCount()
        # 这句是关键！ range(0, rowPosition)[::-1] 逆序循环
        for rP in range(0, rowPosition)[::-1]:
            self.doneui.cardsTW.removeRow(rP)

        self.doneui.totalL_2.setText("NULL")
        self.doneui.countL.setText("NULL")
        self.doneui.allCB.setChecked(False)

        self.DoneFrom.hide()
        self.HomeForm.show()

        self.cbs = []
        self.cbarcodes = {}

    def again(self):
        id = self.doneui.flowCardIdL.text()
        barcodes = []
        for i in list(self.cbarcodes):
            barcodes.append(self.cbarcodes[i])
        with open(f"./config/flowCard/{id}.config", "w+") as fp:
            fp.write(str({'barcodes': barcodes, 'total': len(barcodes), 'count': 0}).replace("'", '"'))

            self.doneui.totalL_2.setText(str(len(barcodes)))
            self.doneui.countL.setText('0')
            self.doneui.printPB.setEnabled(True)

    def all(self):
        if(self.doneui.allCB.isChecked()):
            for item in self.cbs:
                item.setChecked(True)
            for i in range(0, len(self.hbarcodes)):
                self.cbarcodes[str(i)] = self.hbarcodes[i]
        else:
            for item in self.cbs:
                item.setChecked(False)
            self.cbarcodes = {}

    def addCheckBox(self, index):
        widget = QWidget()
        widget.setStyleSheet('border: 0px solid black;')
        #
        selectCB = QCheckBox('')
        selectCB.clicked.connect(lambda: self.select(index, selectCB.isChecked()))
        self.cbs.append(selectCB)

        hLayout = QHBoxLayout()
        hLayout.addWidget(selectCB)
        hLayout.setContentsMargins(50, 2, 2, 5)
        widget.setLayout(hLayout)
        return widget

    def select(self, index, isCheck):
        if (isCheck):
            self.cbarcodes[str(index)] = self.hbarcodes[index]
        else:
            self.cbarcodes.pop(str(index))

    def textChange(self, str):
        if(not str): self.getFlowCards()

    def box(self):
        QMessageBox.information(self.HomeForm, '喷印完成', '喷印计划已完成', QMessageBox.Ok)


class message(QThread):
    signal = pyqtSignal()

    def __init__(self, Window):
        super(message, self).__init__()
        self.window = Window

    def run(self):
        self.signal.emit()

# region 自定义Switch按钮
class SwitchButton(QWidget):
    """自定义Switch按钮"""

    checkedChanged = pyqtSignal(bool)
    def __init__(self, parent=None):
        super(SwitchButton, self).__init__(parent)

        # 设置无边框和背景透明
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        self.resize(70, 30)
        self.state = False  # 按钮状态：True表示开，False表示关

    def mousePressEvent(self, event):
        """鼠标点击事件：用于切换按钮状态"""
        super(SwitchButton, self).mousePressEvent(event)

        self.state = False if self.state else True
        self.checkedChanged.emit(self.state)
        self.update()

    def paintEvent(self, event):
        """绘制按钮"""
        super(SwitchButton, self).paintEvent(event)

        # 创建绘制器并设置抗锯齿和图片流畅转换
        painter = QPainter(self)
        painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)

        # 定义字体样式
        font = QFont('Microsoft YaHei')
        font.setPixelSize(14)
        painter.setFont(font)

        # 开关为开的状态
        if self.state:
            # 绘制背景
            painter.setPen(Qt.NoPen)
            brush = QBrush(QColor('#FF475D'))
            painter.setBrush(brush)
            painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() // 2, self.height() // 2)

            # 绘制圆圈
            painter.setPen(Qt.NoPen)
            brush.setColor(QColor('#ffffff'))
            painter.setBrush(brush)
            painter.drawRoundedRect(93, 6, 24, 24, 12, 12)

            # 绘制文本
            painter.setPen(QPen(QColor('#ffffff')))
            painter.setBrush(Qt.NoBrush)
            painter.drawText(QRect(38, 6, 50, 20), Qt.AlignLeft, '已完成')
        # 开关为关的状态
        else:
            # 绘制背景
            painter.setPen(Qt.NoPen)
            brush = QBrush(QColor('#FFFFFF'))
            painter.setBrush(brush)
            painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height()//2, self.height()//2)

            # 绘制圆圈
            pen = QPen(QColor('#000000'))
            pen.setWidth(1)
            painter.setPen(pen)
            painter.drawRoundedRect(3, 6, 24, 24, 12, 12)

            # 绘制文本
            painter.setBrush(Qt.NoBrush)
            painter.drawText(QRect(38, 6, 50, 20), Qt.AlignLeft, '未完成')
# endregion


if __name__ == '__main__':
    Main()



